﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.IO;

namespace ScriptPacker.Core.Utils
{
    public class XmlUtil
    {
        /// <summary>
        /// to xml 
        /// </summary>
        /// <returns></returns>
        public static string ToXML<T>(T obj)
        {
            string retVal = string.Empty;
            XmlSerializer ss = new XmlSerializer(typeof(T));
            StringBuilder sb = new StringBuilder();
			using (StringWriterWithEncoding sw = new StringWriterWithEncoding(sb, Encoding.UTF8))
			{
				ss.Serialize(sw, obj);
			}
            return sb.ToString();
        }
        
        /// <summary>
        /// to XmlDocument
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static XmlDocument ToXMLDoc<T>(T obj) {
            string xmlStr = ToXML(obj);
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(xmlStr);
            return doc;
        }
        /// <summary>
        /// Deserialize a object from a file
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="xmlFilePath"></param>
        /// <param name="result"></param>
        public static void Deserialize<T>(string xmlFilePath,out T result) {
            result = default(T);
            if (!File.Exists(xmlFilePath)) return;
            XmlReaderSettings xrSettings = new XmlReaderSettings();
            xrSettings.CloseInput = true;
            xrSettings.CheckCharacters = true;
            XmlReader xr = XmlReader.Create(xmlFilePath,xrSettings);
            XmlSerializer xs = new XmlSerializer(typeof(T));
            try
            {
                result = (T)xs.Deserialize(xr);
            }
            catch (Exception ex)
            {
                //do nothing here
            }
            finally {
                xr.Close();
            }
            
        }
    }
}
